package cn.itsource.realm;


import org.apache.commons.lang.StringUtils;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义权限过滤器，覆盖拒绝访问方法
 *
 */
public class MyPermissionsAuthorizationFilter extends PermissionsAuthorizationFilter {

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        //请求对象
        HttpServletRequest req = (HttpServletRequest) request;
        //响应对象
        HttpServletResponse resp = (HttpServletResponse) response;

        String method = req.getMethod();
        if("OPTIONS".equalsIgnoreCase(method)){
            return true;
        }
        //获取头信息
        String header = req.getHeader("X-Requested-With");
        if(StringUtils.isNotBlank(header)){//如果头信息不为空，就证明是ajax请求
            response.setContentType("text/json;charset=utf-8");
            //后台必须返回一个标准的json格式
            response.getWriter().print("{\"success\":false,\"msg\":\"亲!你没有权限访问资源，赶快联系管理员!!\"}");
            return false;
        }else{//如果你不是ajax请求，还是走以前的业务逻辑
            return super.onAccessDenied(request, resp);
        }

    }
}
